package servlet.notice;

import com.alibaba.fastjson.JSONObject;
import utils.JdbcUtil;
import utils.ResultData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/noticeAdd")
public class NoticeAdd extends HttpServlet {
    JdbcUtil jdbcUtil=new JdbcUtil();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String content = req.getParameter("content");
        String user = req.getParameter("user");
        Connection connection = jdbcUtil.getConnection();
        String sql="insert into notice(name,content,user) values(?,?,?)";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultData resultData=null;
            if (name!=null&&name.trim().length()!=0){
                preparedStatement.setString(1,name);
            }else{
                resultData= ResultData.buildMsg(1,"主题不能为空");
            }
            if (content!=null&&content.trim().length()!=0){
                preparedStatement.setString(2,content);
            }else{
                resultData= ResultData.buildMsg(1,"内容不能为空");
            }
            if (user!=null&&user.trim().length()!=0){
                preparedStatement.setString(3,user);
            }else{
                resultData= ResultData.buildMsg(1,"发布者不能为空");
            }
            int i = preparedStatement.executeUpdate();
            if (i>0){
                resultData= ResultData.success();
            }else{
                resultData= ResultData.fail();
            }
            Object o=JSONObject.toJSON(resultData);
            resp.getWriter().print(o.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }
}
